<template>
  <j-modal
    :title="title"
    width="1200px"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    fullscreen
    switchFullscreen
    @ok="handleOk"
    :okButtonProps="{ class:{'jee-hidden': disableSubmit} }"
    @cancel="handleCancel"
    cancelText="关闭">

    <a-spin :spinning="confirmLoading">
      <!-- <j-form-container :disabled="disableSubmit"> -->
        <a-form :form="form" layout="inline" :class="{'online-config-cust':true }">
          <a-list>
            <!-- 表名、表描述、表类型 -->
            <a-list-item>
              <a-row style="width: 100%;">
                <a-col :span="24">
                  <a-row :gutter="gutter" style="width: 100%;">
                    <a-col :span="24/2">
                      <a-form-item
                        style="width: 100%"
                        :labelCol="threeCol.label"
                        :wrapperCol="threeCol.wrapper"
                        label="图层名称">
                        <a-input :disabled="disableSubmit" placeholder="请输入图层名称" v-decorator="['layerName', validatorRules.layerName ]"/>
                      </a-form-item>
                    </a-col>

                    <a-col :span="24/2">
                      <a-form-item
                        style="width: 100%"
                        :labelCol="threeCol.label"
                        :wrapperCol="threeCol.wrapper"
                        label="专题类型">
                          <j-multi-select-tag :disabled="disableSubmit" v-decorator="['topicType',{rules: [{required: false, message: '请选择专题类型！'}]}]" :trigger-change="true" dictCode="sc_situation_index_catalog,catalog_name,catalog_code" placeholder="请选择专题类型" />
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-col>
              </a-row>
            </a-list-item>
            <a-list-item>
              <a-row style="width: 100%;">
                <a-col :span="24">
                  <a-row :gutter="gutter" style="width: 100%;">
                    <a-col :span="24/2">
                      <a-form-item
                        style="width: 100%"
                        :labelCol="threeCol.label"
                        :wrapperCol="threeCol.wrapper"
                        label="图层类型">
                        <a-select :disabled="disableSubmit" placeholder="请选择图层类型" v-decorator="[ 'layerType', validatorRules.layerType]">
                          <a-select-option v-for="(role, roleindex) in layerList" :key="roleindex.toString()" :value="role.value">
                            {{ role.title }}
                          </a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>

                    <a-col :span="24/2">
                      <a-form-item
                        mode="value"
                        style="width: 100%"
                        :labelCol="threeCol.label"
                        :wrapperCol="threeCol.wrapper"
                        label="标签">
                        <a-select :disabled="disableSubmit" placeholder="请选择标签" v-decorator="[ 'labels', validatorRules.labels]">
                          <a-select-option v-for="(role, roleindex) in labelList" :key="roleindex.toString()" :value="role.value">
                            {{ role.title }}
                          </a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-col>
              </a-row>
            </a-list-item>
            <a-list-item>
              <a-row style="width: 100%;">
                <a-col :span="24">
                  <a-row :gutter="gutter" style="width: 100%;">
                    <a-col :span="24/2">
                      <a-form-item
                        style="width: 100%"
                        :labelCol="{span:6}"
                        :wrapperCol="{span:18}"
                        label="关联表">
                        <a-select
                          :disabled="disableSubmit"
                          placeholder="请选择关联表"
                          @change="onChange"
                          v-decorator="[ 'tableName', validatorRules.tableName]">
                          <a-select-option v-for="(role, roleindex) in tableList" :key="roleindex.toString()" :value="role.tableName">
                            {{ role.tableName }}
                          </a-select-option>
                        </a-select>
                      </a-form-item>
                    </a-col>

                    <a-col :span="24/2">
                      <a-form-item
                        style="width: 100%"
                        :labelCol="threeCol.label"
                        :wrapperCol="threeCol.wrapper"
                        label="上传图标">
                          <j-image-upload :disabled="disableSubmit" :isMultiple="false" v-decorator="['layerIcon', validatorRules.layerIcon ]"></j-image-upload>
                      </a-form-item>
                    </a-col>
                  </a-row>
                </a-col>
              </a-row>
            </a-list-item>
          </a-list>
        </a-form>
      <!-- </j-form-container> -->
        <!-- <a-spin :spinning="tableLoading"> -->
        <a-tab-pane tab="数据库属性" key="1" :forceRender="true">
          <db-attribute-table
            ref="table1"
            :disabled="disableSubmit"
            @dragged="handleDragged"/>
        </a-tab-pane>
      <!-- </a-spin> -->
    </a-spin>
  </j-modal>
</template>

<script>

import DBAttrTable from '../util/DBAttrTable'

import { setDataSource } from '../util/TableUtils'
import { validateTables, VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'

import { getAction, httpAction } from '@/api/manage'
import pick from 'lodash.pick'
import { AiTestOnlineMixin } from '@/views/modules/aitest/onlinetest.mixins'

export default {
  name: 'LayerResourceManageModal',
  components: {
    'db-attribute-table': DBAttrTable
  },
  mixins: [AiTestOnlineMixin],
  provide() {
    return {
      getAllTable: this.getAllTable
    }
  },
  props: {
    actionButton: {
      type: Boolean,
      default: true,
      required: false
    }
  },
  data() {
    return {
      title: '操作',
      visible: false,
      activeKey: '1',
      disableSubmit: false,
      model: {},
      gutter: 8,
      layerList: [], // 图层类型
      labelList: [], // 标签类型
      topicList: [], // 专题列表
      tableList: [],
      currSelected: [],
      showRelationType: false,
      showTreeParentIdField: false,
      showIdSequence: false,
      showSubTable: false,
      oneCol: {
        label: { span: 2 },
        wrapper: { span: 24 - 2 }
      },
      threeCol: {
        label: { span: 6 },
        wrapper: { span: 24 - 6 }
      },
      confirmLoading: false,
      tableLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        layerName: {
          rules: [{
            required: true, message: '请输入图层名称!'
          }]
        },
        layerType: { rules: [{ required: true, message: '请选择图层类型!' }] },
        labels: { rules: [{ required: true, message: '请选择标签!' }] },
        tableName: { rules: [{ required: true, message: '请选择关联表!' }] },
        layerIcon: {
          rules: [
            {
              required: true,
              message: '请上传图片!'
            }
          ]
        }
      },
      url: {
        add: '/subject/scSubjectLayerInfo/add/',
        edit: '/subject/scSubjectLayerInfo/edit'
      },
      // 树形列表需要的配置ID集合
      tree_field_id: [],
      // 未验证通过
      VALIDATE_NO_PASSED: Symbol(),
      editPageFlag: false,
      fieldTempIds: [],
      showDesFormCode: false,
      templateFlag: false
    }
  },
  watch: {
  },
  created() {
  },
  mounted() {
  },
  methods: {
    handleChanges(value) {
      console.log('选中项：' + value)
    },
    /**
       * 获取指定的 $refs 对象
       * 有时候可能会遇到组件未挂载到页面中的情况，导致无法获取 $refs 中的某个对象
       * 这个方法可以等待挂载完成之后再返回 $refs 的对象，避免报错
       * @author sunjianlei
       **/
    getRefPromise(name) {
      const _this = this
      return new Promise((resolve) => {
        (function next() {
          const ref = _this.$refs[name]
          if (ref) {
            resolve(ref)
          } else {
            setTimeout(() => {
              next()
            }, 10)
          }
        })()
      })
    },
    initialDictList() {
      getAction('/sys/dict/getDictItems/layer_type').then(res => {
        if (res.success) {
          this.layerList = res.result
        }
      })
      getAction('/sys/dict/getDictItems/subject_labels').then(res => {
        if (res.success) {
          this.labelList = res.result
        }
      })
      getAction('/subject/scSubjectLayerInfo/getTopicList').then(res => {
        if (res.success) {
          this.topicList = res.result
        }
      })
      getAction('/subject/scSubjectLayerInfo/listAllTableInfo').then(res => {
        if (res.success) {
          this.tableList = res.result
        }
      })
    },
    // 关联表选择后，获取数据库属性
    onChange(selectedValue) {
      const data = this.tableList.filter(d => d.tableName === selectedValue)
      for (const table of data[0].columns) {
        table.isShowList = 1
        table.isShowForm = 1
        table.columnDesc = table.columnComment
      }
      console.log('data:', data)
      this.initData(data[0].columns)
    },
    initData(datas) {
      this.getAllTable().then(tables => {
        const [table1] = tables
        // 临时 id，不保存到数据库
        const tempIds = []
        datas.forEach((data, index) => {
          data.dbIsKey = 0
          tempIds.push(data.id)
        })
        this.fieldTempIds = tempIds
        // setTimeout 是为了解除添加初始化数据的时候卡住的问题，先让弹窗弹出来，再添加数据
        setTimeout(() => {
          setDataSource(table1, datas)
        }, 1)
      })
    },
    add() {
      this.addFlag = true
      this.edit({})
    },
    edit(record) {
      this.initialDictList()
      if (record.id) {
        this.initData(record.layerDetails)
      }
      this.initialAllTable()
      this.visible = true
      // 设置主表的数据
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.model.disabled = this.disableSubmit
      this.model.tableName = this.model.relTable
      const pickAfter = pick(this.model, 'dataSource', 'layerName', 'topicType', 'tableName', 'layerIcon', 'layerType', 'labels')
      this.$nextTick(() => {
        this.form.setFieldsValue(pickAfter)
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      if (this.disableSubmit) return
      this.validateFields()
    },
    handleCancel() {
      this.close()
    },

    /** 初始化所有需要条件切换显示的项 */
    initialAllShowItem(record) {
    },

    handleChangeInIdType(value) {
      this.showIdSequence = (value === 'SEQUENCE')
    },

    /* tables function */

    /** 获取所有的表 */
    getAllTable() {
      return Promise.all([
        this.getRefPromise('table1')
      ])
    },

    /** 初始化所有的table */
    initialAllTable() {
      this.getAllTable().then(tables => {
        tables.forEach(table => {
          table.$refs.editableTable.initialize()
        })
      })
    },

    /** 当拖动后立即同步 */
    handleDragged(event) {
      const { oldIndex, newIndex, target } = event
      this.syncAllOrderNumNow(oldIndex, newIndex)
    },

    /** 立即同步所有的表的排序顺序 */
    syncAllOrderNumNow(oldIndex, newIndex) {
      this.getAllTable().then(tables => {
        tables.forEach((tab, idx) => {
          if (idx > 0 && idx < 4) {
            tab.$refs.editableTable.rowResort(oldIndex, newIndex)
          }
        })
      })
    },

    /** 立即主动同步所有table */
    syncAllTableNow() {
      // this.syncAllTableNowDebounce()
    },

    /** 触发所有表单验证 */
    validateFields() {
      this.confirmLoading = true
      const options = {}
      new Promise((resolve, reject) => {
        // 验证主表表单
        this.form.validateFields((error, values) => {
          console.log('values:', values)
          if (error) {
            reject(VALIDATE_NO_PASSED)
          } else {
            resolve({ values })
          }
        })
      }).then((result) => {
        Object.assign(options, result)
        // 验证所有tables的表单
        return this.validateTableFields()
      }).then(values => {
        Object.assign(options, values)
        const formData = this.classifyIntoFormData(options)
        return this.requestAddOrEdit(formData)
      }).catch(e => {
        this.confirmLoading = false
        if (e.error !== VALIDATE_NO_PASSED) {
          console.error(e)
        }
      })
    },

    /** 发起请求新增或修改的请求 */
    requestAddOrEdit(formData) {
      this.confirmLoading = true
      // 判断是add还是edit
      let method = 'post'; let url = this.url.add + this.currSelected.id
      if (this.model.id) {
        method = 'put'
        url = this.url.edit
      }
      formData.groupId = this.currSelected.id
      // 发起请求
      httpAction(url, formData, method).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.$emit('ok')
          this.close()
        } else {
          this.$message.warning(res.message)
        }
      }).finally(() => {
        this.confirmLoading = false
      })
    },

    /** 将五个表的数据整理整合成后台识别的formData */
    classifyIntoFormData(options) {
      this.model.layerDetails = []
      // 整理数据
      const formData = Object.assign(this.model, options.values)
      this.model.relTable = this.model.tableName
      console.log(this.model)

      // 整理 fields
      options.table1.values.forEach((item, index) => {
        const field = Object.assign({}, item)
        formData.layerDetails.push(field)
      })

      return formData
    },

    /** 验证并获取五个表的数据 */
    validateTableFields() {
      const _this = this
      return new Promise((resolve, reject) => {
        this.getAllTable().then((tables) => {
          const cases = []
          for (const table of tables) {
            cases.push(table.$refs.editableTable)
          }
          return validateTables(cases, true)
        }).then((all) => {
          const options = {}
          all.forEach((item, index) => {
            options[`table${index + 1}`] = item
          })
          resolve(options)
        }).catch((e = {}) => {
          // 判断表单验证是否未通过
          if (e.error === VALIDATE_NO_PASSED) {
            // 未通过就跳转到相应的tab选项卡
            _this.activeKey = (e.index + 1).toString()
          }
          reject(e)
        })
      })
    }
  }
}
</script>

<style scoped>
 .online-config-cust .has-feedback{display: block !important;}
 .input-table .thead .td span{width:100%}
</style>
